<?php
namespace app\service\data;

use app\service\models as models;
use app\lib\Encryption;
use Yii;
use app\lib\Code;

class Sms {
    
//     private $_signName = 'Detrust';
    
//     private $_registerTemplateCode = 'SMS_136381373';
    
    private $_signName = 'OCT人工智能识别平台';
    
    private $_registerTemplateCode = 'SMS_139242703';
    
    private $_registerRedisKey = 'oct|sms|code|%s'; //手机号码
    
    public function __construct() {
    
    }
    
    public function Register($arrInput) {
        $phone = $arrInput['phone'];
        $redisKey = sprintf($this->_registerRedisKey, $phone);
        $code_check = Yii::$app->cache->get($redisKey.'ttl');
        if($code_check) {
            formatJson(Code::PARAM, '操作太快');
        }
        $code = Encryption::getsalt(4);
        //存储验证码
        $ret = Yii::$app->cache->set($redisKey, $code);
        if(!$ret) {
            formatJson(Code::PARAM, '验证码保存失败');
        }
        //180秒过期
        $ret = Yii::$app->cache->expire($redisKey, 180);
        if(!$ret) {
            formatJson(Code::PARAM, '设置有效期失败');
        }
        
        //60秒内不能再次获取验证码
        $ret = Yii::$app->cache->set($redisKey.'ttl', $code);
        if(!$ret) {
            formatJson(Code::PARAM, '频率限制保存失败');
        }
        $ret = Yii::$app->cache->expire($redisKey.'ttl', 60);
        if(!$ret) {
            formatJson(Code::PARAM, '频率限制失败');
        }
        
        $msg = models\Sms::sendSms($phone, $this->_signName, $this->_registerTemplateCode, ["code"=>$code]);
        //校验
        if($msg->Code != 'OK') {
            formatJson($msg->Code, $msg->Message);
        }
        
        return true;
    }
}